package com.nowcoder.service;

import com.nowcoder.dao.LoginTicketDAO;
import com.nowcoder.dao.UserDAO;
import com.nowcoder.model.LoginTicket;
import com.nowcoder.model.User;
import com.nowcoder.utils.ToutiaoUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.support.DaoSupport;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by nowcoder on 2016/7/2.
 */
@Service
public class UserService {

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private LoginTicketDAO loginTicketDAO;

    public User getUser(int id) {
        return userDAO.selectById(id);
    }

    //返回一个Map，里面装的是Json信息：如果没有注册成功，则会返回原因，如果注册成功则会返回ticket
    public Map<String,Object> register(String username, String password) {
        Map<String,Object> map = new HashMap<String,Object>();
        if(StringUtils.isBlank(username)) {
            map.put("msgname","用户名不能为空！");
            return map;
        }
        if(StringUtils.isBlank(password)) {
            map.put("msgpwd","密码不能为空！");
            return map;
        }

        User user = userDAO.selectByName(username);
        if(user!=null) {
            map.put("msgname","用户名已经被注册！");
            return map;
        }

        //加salt+添加用户
        user = new User();
        String head = String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000));
        user.setHeadUrl(head);
        user.setName(username);
        String salt = UUID.randomUUID().toString().substring(0,5);
        user.setSalt(salt);
        user.setPassword(ToutiaoUtil.MD5(password+salt));
        userDAO.addUser(user);

        //登陆并返回ticket
        String ticket = addLoginTicket(user.getId());
        map.put("ticket",ticket);
        return map;

    }

    private String addLoginTicket(int userId) {
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setTicket(UUID.randomUUID().toString().replaceAll("-",""));
        loginTicket.setStatus(0);
        Date date = new Date();
        date.setTime(date.getTime()+1000*3600*24);
        loginTicket.setExpired(date);
        loginTicket.setUserId(userId);
        loginTicketDAO.addTicket(loginTicket);
        return loginTicket.getTicket();
    }
}
